
App.directive('edValidate', function() {
    return {
        restrict:"A",
        require:"ngModel",
        link:function(scope, elem, attrs, ngModelController){
            ngModelController.$parsers.push(function(viewValue) {
                var type = attrs.edValidate;
                if (type) {
                    var pattern;
                    if (type == 'phone') {// 验证电话号码
                        pattern = /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i;
                        $(elem).attr('patternMsg', '格式不正确,请使用下面格式:010-88888888');
                    } else if (type == 'mobile') {// 验证手机号码
                        pattern = /^(13|15|18|17)\d{9}$/i;
                        $(elem).attr('patternMsg', '手机号码格式不正确');
                    } else if (type == 'phoneOrMobile') {// 验证手机或电话
                        var vali = /^(13|15|18|17)\d{9}$/i.test(viewValue) || /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(viewValue);
                        ngModelController.$setValidity('pattern', vali);
                        $(elem).attr('patternMsg', '请填入手机或电话号码');
                    } else if (type == 'integer') {// 验证整数
                        pattern = /^[+]?[1-9]+\d*$/i;
                        $(elem).attr('patternMsg', '请输入整数');
                    } else if (type == 'chinese') {// 验证中文
                        pattern = /^[\u0391-\uFFE5]+$/i;
                        $(elem).attr('patternMsg', '请输入中文');
                    } else if (type == 'english') {// 验证英语
                        pattern = /^[A-Za-z]+$/i;
                        $(elem).attr('patternMsg', '请输入英文');
                    } else if (type == 'username') {// 验证用户名
                        pattern = /^[a-zA-Z][a-zA-Z0-9_]{5,15}$/i;
                        $(elem).attr('patternMsg', '用户名不合法（字母开头，允许6-16字节，允许字母数字下划线');
                    } else if (type == 'name') {// 验证姓名，可以是中文或英文
                        pattern = /^[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5a-zA-Z0-9_]+$/;
                        var label = $(elem).parents('.form-group:eq(0)').find('label');
                        var message = '名称格式不正确';
                        if (label) {
                            message = label.text() + "格式不正确";
                        }
                        $(elem).attr('patternMsg', message);
                    } else if (type == 'email') {
                        pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                        $(elem).attr('patternMsg', '请输入有效的电子邮件账号(例：abc@126.com)');
                    }
                    if (pattern) {
                        ngModelController.$setValidity('pattern', pattern.test(viewValue));
                    }
                }
                return viewValue;
            });
        }
    };
});